using System;
using Microsoft.SPOT;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace Ranzmaier.NETMF.GadgeteerNetworking
{
    public abstract class NetClientBase : IDisposable
    {

        protected Socket _socket;
        /// <summary>
        /// Gets a value indicating whether this <see cref="TcpClient"/> is active.
        /// </summary>
        /// <value>
        ///   <c>true</c> if active; otherwise, <c>false</c>.
        /// </value>
        public bool Active { get; protected set; }

        public Socket Client
        {
            get
            {
                return _socket;
            }
        }

        public abstract void Connect(string hostname, int port);
        public abstract void Connect(IPEndPoint ep);


        public NetClientBase()
        {
            Active = false;

        }

        public NetClientBase(IPEndPoint ep)
        {
            Connect(ep);
        }
        public NetClientBase(string hostname, int port)
        {
            Connect(hostname, port);

        }

        /// <summary>
        /// Closes and dispose this instance.
        /// </summary>
        public void Close()
        {
            ((IDisposable)this).Dispose();
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        public virtual void Dispose()
        {
            Socket socket = _socket;
            if (_socket != null)
                socket.Close();
            _socket = null;
        }


        protected void Connect(string hostname, int port, ProtocolType type)
        {
            if (hostname == null || hostname == string.Empty)
                throw new ArgumentNullException("hostname");
            if (port < 0 || port > 65535)
                throw new ArgumentOutOfRangeException("port");

            Socket tmpSocket = null;
            Exception lastException = null;

            try
            {
                var hosts = Dns.GetHostEntry(hostname);

                for (int i = 0; i < hosts.AddressList.Length; i++)
                {
                    IPAddress iPAddress = hosts.AddressList[i];
                    try
                    {

                        if (_socket == null)
                        {
                            tmpSocket = new Socket(AddressFamily.InterNetwork, type == ProtocolType.Udp ? SocketType.Dgram : SocketType.Stream, type);
                            tmpSocket.Connect(new IPEndPoint(iPAddress, port));
                            _socket = tmpSocket;
                            Active = true;
                            break;
                        }
                    }
                    catch (SocketException se)
                    {
                        if (se.ErrorCode == 10024) //TooManyOpenFiles/TooManyOpenSockets
                        {
                            var freed = Debug.GC(true);
                            Debug.Print("GC returns " + freed + "bytes");



                        }
                        throw;

                    }
                    catch (Exception ex)
                    {
                        if (ex is ThreadAbortException || ex is OutOfMemoryException)
                        {
                            throw;
                        }
                        lastException = ex;
                    }
                }
            }
            catch (Exception ex)
            {
                lastException = ex;

            }
            finally
            {
                if (!Active)
                {
                    if (_socket != null)
                        _socket.Close();
                    if (tmpSocket != null)
                        tmpSocket.Close();
                    if (lastException != null)
                        throw lastException;
                }
            }

        }
    }
}
